package com.easyidea.its.domain.repository.base.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

import org.hibernate.Session;

import com.infowarelab.persistence.filter.base.Filter;
import com.infowarelab.persistence.hibernate.PersistenceHibernateImpl;
import com.easyidea.its.domain.model.BaseEntity;
import com.easyidea.its.domain.repository.base.ExtendPersistenceIF;

public class ExtendPersistenceImpl extends PersistenceHibernateImpl implements ExtendPersistenceIF {

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.infowarelab.cim.service.CimPersistenceIF#delete(java.lang.Object)
	 */
	public void delete(Object entity) {
		if (entity instanceof BaseEntity) {
			BaseEntity newObj = (BaseEntity) entity;
			newObj.setDeleted(true);
			newObj.setModifyTime(new Date());
			update(newObj);
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.infowarelab.cim.service.CimPersistenceIF#delete(com.infowarelab.persistence.filter.base.Filter)
	 */
	public void delete(Filter filter) {
		Collection objs = query(filter);
		for (Iterator iter = objs.iterator(); iter.hasNext();) {
			Object obj = iter.next();
			delete(obj);
		}
	}

	/**
	 * implement by Denny.
	 */
	public Collection executePureSqlByConnection(String sql) {
		Collection<Object> list = new ArrayList<Object>();

		Session session = this.getHibernateTemplate().getSessionFactory()
				.openSession();
		Connection connection = session.connection();
		Statement st = null;
		ResultSet rs = null;
		try {
			st = connection.createStatement();
			rs = st.executeQuery(sql);
		} catch (SQLException e) {
			log.error(e);
		}

		try {
			while (rs.next()) {
				int columnCount = rs.getMetaData().getColumnCount();
				Object[] resultObject = new Object[columnCount];
				for (int j = 1; j <= columnCount; j++) {
					resultObject[j - 1] = rs.getObject(j);
				}
				list.add(resultObject);
			}
		} catch (SQLException e) {
			log.error(e);
		}
		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
				log.error(e);
			}
		}
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				log.error(e);
			}
		}
		session.close();
		return list;
	}
	
}
